import React, { useEffect } from 'react';
import { Radio, Input, Button } from 'antd';
export default class Voice extends React.Component {
  // const startBtn = React.createRef();

  // handeStartClick = () => {

  // }

  componentDidMount() {
    if (navigator.mediaDevices) {
      // 获取打开麦克风权限，以及stream对象
      navigator.mediaDevices
        .getUserMedia({ audio: true })
        .then((stream) => {
          var chunks = [];
          // 创建MediaRecorder对象，需要传入stream对象
          var mediaRecorder = new MediaRecorder(stream);

          var startBtn = document.getElementsByTagName('button')[0];
          var stopBtn = document.getElementsByTagName('button')[1];
          console.log(startBtn);

          // 开始
          startBtn.onclick = () => {
            // 开始录音
            mediaRecorder.start();
          };
          // 结束
          stopBtn.onclick = () => {
            // 停止录音
            mediaRecorder.stop();
          };

          // 添加事件监听
          mediaRecorder.onstart = () => {
            console.log('start', mediaRecorder.state);
          };
          mediaRecorder.onstop = () => {
            console.log('stop', mediaRecorder.state);
            // 数据块合成blob对象
            var blob = new Blob(chunks, { type: 'audio/webm;codecs=opus' });
            console.log(blob);

            var audio = document.getElementsByTagName('audio')[0];
            var url = (window.URL || webkitURL).createObjectURL(blob);
            audio.src = url;
            audio.controls = true;
            //   document.body.appendChild(audio);
            console.log(audio, url);
          };
          mediaRecorder.ondataavailable = (e) => {
            console.log('data');
            console.log(e);
            chunks.push(e.data);
          };
        })
        .catch((e) => {
          console.log(e);
        });
    }
  }
  render() {
    return (
      <div>
        <Button>开始录音</Button>
        <Button>结束录音</Button>
        <audio></audio>
        {/* {this.props.audioUrl && this.props.aduioUrl(audio.src)} */}
      </div>
    );
  }
}
